<?php

namespace app\oauth\controller;

use app\BaseController;

use think\exception;
use think\facade\View;
use think\facade\Session;



use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

use League\OAuth2\Server\Exception\OAuthServerException; //异常

use app\oauth\library\OauthServer;

class Oauth extends Controller
{


    //获得token
    public function issueToken()
    {

        $server = new OauthServer();

        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;

        try {
            // 这里只需要这一行就可以，具体的判断在 Repositories 中
            return $server->respondToAccessTokenRequest($request, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }


    //授权码模式
    public function authorize()
    {


        $server = new OauthServer();


        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;

        try {

            // 验证 HTTP 请求，并返回 authRequest 对象
            $authRequest = $server->validateAuthorizationRequest($request);

            // 此时应将 authRequest 对象序列化后存在当前会话(session)中
            Session::set('authRequest', serialize($authRequest));



            $client = $authRequest->getClient()->getIdentifier();

            $scopes = '';
            if (is_array($authRequest->getScopes())) {

                $ids = [];
                foreach ($authRequest->getScopes() as $scope) {
                    $ids[] = $scope->getIdentifier();
                }

                $scopes = $ids[0];
            }


            Session::set("authToken", $authToken = "abc123456");

            // dump(Session::get("authToken"));exit();

            // dump($this->request);exit();

            $data = [
                'client' => $client,
                // 'user' => $user,
                'scopes' => $scopes,
                'request' => $this->request,
                'authToken' => $authToken,
                'state' => $this->request->param('state'),
            ];


            View::assign('data', $data);

            return View::fetch('oauth/login');
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {

            // 可以捕获 OAuthServerException，将其转为 HTTP 响应
            // dump ($exception->generateHttpResponse($response));exit();
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {

            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }


    //登陆授权页
    public function approve()
    {

        $server = new OauthServer();

        $response = new \GuzzleHttp\Psr7\Response;

        try {
            // 在会话(session)中取出 authRequest 对象
            $authRequest = unserialize(Session::get('authRequest'));

            // print_r(new \app\index\Entities\UserEntity(1));exit();

            // 设置用户实体(userEntity)
            $authRequest->setUser(new \app\oauth\Entities\UserEntity());
            
            // 设置权限范围
            // $authRequest->setScopes(['basic']);

            // true = 批准，false = 拒绝
            $authRequest->setAuthorizationApproved(true);

            // 完成后重定向至客户端请求重定向地址
            return $server->completeAuthorizationRequest($authRequest, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
            // 可以捕获 OAuthServerException，将其转为 HTTP 响应
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {

            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }



    //隐式授权模式
    public function implicit()
    {



        $server = new OauthServer();


        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;

        try {
            $authRequest = $server->validateAuthorizationRequest($request);
            $authRequest->setUser(new \app\oauth\Entities\UserEntity());
            $authRequest->setAuthorizationApproved(true);
            return $server->completeAuthorizationRequest($authRequest, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }



    //刷新token
    public function refresh()
    {



        $server = new OauthServer();

        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;


        try {
            // 这里只需要这一行就可以，具体的判断在 Repositories 中
            return $server->respondToAccessTokenRequest($request, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }

    //客户端模式
    public function client()
    {

        $server = new OauthServer();


        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;

        try {
            // 这里只需要这一行就可以，具体的判断在 Repositories 中
            return $server->respondToAccessTokenRequest($request, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }


    public function password()
    {


        $server = new OauthServer();

        $request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
        $response = new \GuzzleHttp\Psr7\Response;

        try {
            // 这里只需要这一行就可以，具体的判断在 Repositories 中
            return $server->respondToAccessTokenRequest($request, $response);
        } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {

            return $exception->generateHttpResponse($response);
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return json($e->getMessage());
        }
    }
}
